package com.kye.addrpicker;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;

import com.kye.addrpicker.model.AddressPickerResult;
import com.kye.addrpicker.model.City;

/**
 * TODO 遗留问题：
 * 1.热门城市数据如何来
 * 2.定位城市和热门城市如何获取它上面的，比如说省份等, 如何获取它当前的等级
 * TODO 注意事项：
 * 记得在调用的module中加入百度的：
 * <meta-data
 * android:name="com.baidu.lbsapi.API_KEY"
 * android:value="BDkrlSp5O2F56GRU8G3t5ZAA1De2VGte" >
 * </meta-data>
 * 和混淆打包内容
 */
public class AddressPickerActivity extends AppCompatActivity implements PickerListener {
    public static final String KEY_ARG_PICKED_RESULT = "picked_city";
    public static final String KEY_ARG_NEED_TO_LEVEL = "need_to_level";
    public static final String KEY_ARG_TITLE = "title";
    public static final String PARAM_PARENT_FIRST = "-1";//用来判断是否是第一次添加
    public static final int ADDRESS_PICKER_ACTIVITY_REQUEST_CODE = 1;
    private Toolbar mToolbar;


    public static void startActivityForResult(Activity activity, String title, Levels levels, int requestCode) {
        activity.startActivityForResult(
                new Intent(activity, AddressPickerActivity.class)
                .putExtra(AddressPickerActivity.KEY_ARG_TITLE, title)
                .putExtra(AddressPickerActivity.KEY_ARG_NEED_TO_LEVEL, levels),
                requestCode
        );
    }

    public static void startActivityForResult(Activity activity, String title, Levels levels) {
        startActivityForResult(activity, title, levels, ADDRESS_PICKER_ACTIVITY_REQUEST_CODE);
    }

    public static enum Levels {
        province, city, area, street
    }

    private Levels mCurrentNeedPickerLevel = Levels.province;//需要选择到哪个级别
    private String mTitle = "";//页面标题，需要从调用地方传入

    private AddressPickerResult mResult;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cp_activity_city_list);
        try {
            mTitle = getIntent().getStringExtra(KEY_ARG_TITLE);
            mCurrentNeedPickerLevel = (Levels) getIntent().getSerializableExtra(KEY_ARG_NEED_TO_LEVEL);
        } catch (Exception e) {
            //TODO 参数有误
        }
        if (!TextUtils.isEmpty(mTitle)) {
            setTitle(mTitle);
        }
        mResult = new AddressPickerResult();

        City city = new City();
        city.setParentID(PARAM_PARENT_FIRST);
        addFragment(city);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        final ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);

        setTitle(mTitle);
    }

    private void addFragment(City pickedCity) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        AddressPickerFragment fragment = AddressPickerFragment.newInstances(pickedCity);
        ft.replace(R.id.fgcontains, fragment);
        ft.addToBackStack(null);//不需要返回上一层把这行去掉
        ft.commit();
    }

    /**
     * 返回地址选择结果
     */
    private void backWithData() {
        Intent data = new Intent();
        data.putExtra(KEY_ARG_PICKED_RESULT, mResult);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onPicked(City pickedCity) {
        if (mResult != null) {
            switch (pickedCity.getLevelType()) {
                case "1":
                    mResult.setProvince(pickedCity.getFullName());
                    break;
                case "2":
                    mResult.setCity(pickedCity.getFullName());
                    break;
                case "3":
                    mResult.setArea(pickedCity.getFullName());
                    break;
                case "4":
                    mResult.setStreet(pickedCity.getFullName());
                    break;
            }
            int levelType = 1;
            try {
                levelType = Integer.valueOf(pickedCity.getLevelType());
            } catch (Exception e) {

            }
            if (levelType >= (mCurrentNeedPickerLevel.ordinal() + 1)) {
                backWithData();
            } else {
                addFragment(pickedCity);
            }
        }
    }

    /**
     * 后退的时候按栈回退
     */
    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            getSupportFragmentManager().popBackStackImmediate();
        } else {
            finish();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
